<template>
  <a-row>
    <div class="total-table-container">
      <a-row style="margin-bottom: 8px;">
        <!-- @click="toAddPage" -->
        <a-col :span="4">
          <!-- <a-button class="editable-add-btn" type="primary">新建</a-button> -->
        </a-col>
        <a-col :span="2" push="18" style="text-align: right;">
          <ExportFile
            :fetch="getDownloadData"
            :fields="jsonFields"
            name="downloadFile.xls"
          >
            <a-button
              class="editable-add-btn"
              type="primary"
              :loading="iconLoading"
              >导出</a-button
            >
          </ExportFile>
        </a-col>
      </a-row>

      <a-row>
        <a-table
          :columns="tableColumns"
          :data-source="tableDataLists"
          :scroll="{ x: 1200 }"
          :rowKey="
            (record, index) => {
              return index;
            }
          "
          :pagination="paginationOpt"
          :loading="isLoading"
          bordered
          @change="handleTableChange"
        >
          <template slot="engineers" slot-scope="text, record, index">
            <div class="engineersBox">
              <div class="card" v-for="(item, index) in text" :key="index">
                <div class="row">
                  <span class="label">片区</span><span class="separator">:</span
                  ><span class="text">{{ item.secondDepartment }}</span>
                </div>
                <div class="row">
                  <span class="label">现场维修工程师</span
                  ><span class="separator">:</span
                  ><span class="text">{{ item.name }}</span>
                </div>
                <div class="row">
                  <span class="label">手机号</span
                  ><span class="separator">:</span
                  ><span class="text">{{ item.username }}</span>
                </div>
                <div class="row">
                  <span class="label">工作天数</span
                  ><span class="separator">:</span
                  ><span class="text">{{ item.day }}</span>
                </div>
                <div class="row">
                  <span class="label">处理设备数量</span
                  ><span class="separator">:</span
                  ><span class="text">{{ item.resolveNcNumber }}</span>
                </div>
                <div class="row">
                  <span class="label">金额</span><span class="separator">:</span
                  ><span class="text">{{ item.money }}</span>
                </div>
              </div>
            </div>
          </template>
        </a-table>
      </a-row>
    </div>
  </a-row>
</template>

<script>
import api from "@/server/userConfig";
import { buildLinkSelect, getRoleId } from "@/unit/tool";
import { RepairResultType } from "@/unit/constantValue";
import { columns, subColumns } from "./tableConfig";
import { AssignRules, FixDoneRules, FinishRules } from "./rulesConfig";
import ExportFile from "vue-json-excel";

function buildJsonFields(lists) {
  let jsonFields = {};
  lists.forEach((item, index) => {
    if (item.dataIndex != "operateStatus") {
      jsonFields[item.title] = item.dataIndex;
    }
  });
  return jsonFields;
}

export default {
  name: "HistoryOrderTable",
  props: {
    searchData: Object
  },
  components: {
    ExportFile
  },
  data() {
    return {
      userName: "",
      role: "",
      compId: "",
      tableColumns: columns,
      subTableColumns: subColumns,
      tableDataLists: [],
      isLoading: false,
      paginationOpt: {
        current: 1,
        defaultCurrent: 1, // 默认当前页数
        defaultPageSize: 3, // 默认当前页显示数据的大小
        total: 0, // 总数，必须先有
        showTotal: total => `共 ${total} 条`, // 显示总数
        // 点击分页时事件
        onChange: (current, size) => {
          let { rangeTime, ...rest } = this.searchData;
          this.paginationOpt.current = current;
          this.getAreaDetail({ pageNum: current }, "tableDataLists");
        }
      },
      iconLoading: false,
      jsonFields: buildJsonFields(columns)
    };
  },
  computed: {},
  watch: {
    searchData: {
      immediate: true,
      deep: true,
      handler: function(newVal, oldVal) {
        // this.paginationOpt.current = 1;
        this.getAreaDetail({ pageNum: 1 }, "tableDataLists");
      }
    }
  },
  created() {},
  mounted() {
    getRoleId(this);
  },
  methods: {
    handleTableChange(pagination) {
      // debugger
      // this.paginationOpt.current = pagination.current;
    },
    // 获取片区间收支详情
    async getAreaDetail(parames, key) {
      let _this = this;
      _this.isLoading = true;
      console.log(this.searchData);
      let {
        rangeTime,
        startTime,
        endTime,
        ...restSearchData
      } = _this.searchData;
      let { defaultPageSize, current, timeType } = this.paginationOpt;
      // let { startTime, endTime, ...rest } = parames;

      const res = await api.getAreaDetail({
        // mainArea: "华中片区",
        // relatedArea: "湖南分公司",
        // type: 0,
        // startTime: "2020-01-30 00:44:55",
        // endTime: "2021-05-30 00:44:55",
        startTime: `${startTime} 00:00:00`,
        endTime: `${endTime} 23:59:59`,
        pageSize: defaultPageSize,
        ...restSearchData,
        ...parames
      });
      _this.isLoading = false;

      if (res.MsgCode !== 0) {
        return;
      }
      let { Data } = res;
      this.paginationOpt.total = Data.total;
      this[key] = Data.rows;
      console.log(key, Data.rows);
    },

    // 点击每一行的跳转;
    clickSingleRow(record, index) {
      return {
        on: {
          click: () => {
            // 实现跳转;
            // window.open(`/#/productRepairDetail?id=${record.repairId}`);
            // let { area } = record;
            // this.$router.push({
            //   name: "areaStatisticsDetail",
            //   params: { district: area }
            // });
          }
        }
      };
    },
    // 获取需要导出的数据
    async getDownloadData() {
      let _this = this;
      if (_this.iconLoading == true) {
        return false;
      }
      let total = _this.paginationOpt.total;
      let pageSize = 300;
      let length = Math.ceil(total / pageSize);
      let newLists = [];
      _this.iconLoading = true;
      for (let i = 1; i <= length; i++) {
        let lists = await this.buildDownloadLists({
          pageNum: i,
          pageSize: pageSize
        });
        newLists.push(lists);
      }
      _this.iconLoading = false;
      return [].concat(...newLists);
    },

    async buildDownloadLists(parames) {
      let _this = this;
      let { pageNum, pageSize } = parames;
      let {
        rangeTime,
        startTime,
        endTime,
        ...restSearchData
      } = _this.searchData;
      const res = await api.getAreaDetail({
        startTime: `${startTime} 00:00:00`,
        endTime: `${endTime} 23:59:59`,
        ...restSearchData,
        ...parames
      });
      if (res.MsgCode !== 0) {
        return;
      }

      let list = buildLists(res.Data.rows);
      return list;

      function buildLists(lists) {
        return lists.map((item, index) => {
          try {
            let newItem = format(item);
            return newItem;
          } catch (e) {
            console.log(e);
          }
        });
      }

      function format(item) {
        if (item.repairOrderNumber) {
          item.repairOrderNumber = `'${item.repairOrderNumber}'`;
        }
        if (item.engineers) {
          item.engineers = formatEngineers(item.engineers);
        }
        return item;
      }

      function formatEngineers(lists) {
        let str = "";
        lists.forEach((item, index) => {
          str += `${item.secondDepartment}:${item.name}(${item.username}),工作${item.day}天,处理设备${item.resolveNcNumber}台,结算金额${item.money}元;`;
        });

        return str;
      }
    }
  }
};
</script>

<style lang="css" scoped>
@import "./style.css";
.itemWrap {
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  justify-content: flex-start;
  align-items: center;
}

.itemWrap > .label {
  min-width: 90px;
  font-size: 16px;
  font-family: Microsoft YaHei;
  font-weight: 400;
  color: #373737;
  text-align: right;
}

.itemWrap > .separator {
  padding: 0px 4px;
}

.itemWrap > .content {
  width: 100%;
  padding: 0px 1px;
}

.engineersBox {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  justify-content: flex-start;
  align-items: center;
}

.engineersBox .card {
  width: 170px;
  border: 1px solid #e8e8e8;
  padding: 8px 4px;
  border-radius: 4px;
  margin-right: 4px;
}

.engineersBox .row {
  text-align: left;
}

.engineersBox .label {
  /* text-align: left; */
}

.engineersBox .separator {
}

.engineersBox .text {
  /* text-align: left; */
}
</style>
